<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>人机五子棋</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <style>
        /* 保持原有样式不变 */
        body { display: flex; flex-direction: column; align-items: center; background: #f0f0f0; }
        #board { background: #DEB887; padding: 20px; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.2); }
        .grid { display: grid; grid-template-columns: repeat(15, 40px); grid-template-rows: repeat(15, 40px); gap: 1px; }
        .cell { background: rgba(255, 255, 255, 0.1); cursor: pointer; position: relative; }
        .stone { width: 30px; height: 30px; border-radius: 50%; position: absolute; top: 50%; left: 50%; transform: translate(--50%,-50%); }
        .black { background: #333; }
        .white { background: #fff; }
        #status { font-size: 24px; margin: 10px; }
        button { padding: 10px 20px; background: #4CAF50; color: white; border: none; border-radius: 5px;margin-top: 10px; }
    </style>
<style>
    /* 修正后 */
    .stone {
        transform: translate(-50%, -50%); /* 修正坐标符号 */
    }

    /* 补充调整布局 */
    .cell {
        position: relative;
        width: 40px;
        height: 40px;
    }
</style>
</head>
<body>
    <h1>人机五子棋</h1>
    <div id="status">你的回合（黑棋）</div>
    <div id="board"><div class="grid" id="grid"></div></div>
    <button onclick="resetGame()">重新开始</button>

    <script>
        let humanPlayer = 1;  // 人类玩家为黑棋
        let aiPlayer = 2;     // AI为白棋
        let currentPlayer = humanPlayer;
        let gameOver = false;
        const board = Array(15).fill().map(() => Array(15).fill(0));

        // 初始化棋盘
        function initBoard() {
            const grid = document.getElementById('grid');
            grid.innerHTML = '';
            for(let i=0; i<15; i++) {
                for(let j=0; j<15; j++) {
                    const cell = document.createElement('div');
                    cell.className = 'cell';
                    cell.dataset.row = i;
                    cell.dataset.col = j;
                    cell.addEventListener('click', handleHumanClick);
                    grid.appendChild(cell);
                }
            }
        }

        // 人类玩家落子
        function handleHumanClick(e) {
            if(gameOver || currentPlayer !== humanPlayer) return;
            
            const row = +e.target.dataset.row;
            const col = +e.target.dataset.col;
            
            if(board[row][col] === 0) {
                placeStone(row, col, humanPlayer);
                if(checkWin(row, col)) {
                    gameOver = true;
                    document.getElementById('status').textContent = '你获胜了！';
                    // 设置文字颜色为红色
                    document.getElementById('status').style.color = 'red';
                    return;
                }
                currentPlayer = aiPlayer;
                document.getElementById('status').textContent = 'AI思考中...';
                setTimeout(aiMove, 500); // AI延迟500毫秒落子
            }
        }

        // AI落子逻辑
        function aiMove() {
            if(gameOver) return;
            
            // 寻找最佳落子点
            let bestMove = findBestMove();
            if(bestMove) {
                placeStone(bestMove.row, bestMove.col, aiPlayer);
                if(checkWin(bestMove.row, bestMove.col)) {
                    gameOver = true;
                    document.getElementById('status').textContent = 'AI获胜！';
                    // 设置文字颜色为红色
                    document.getElementById('status').style.color = 'blue';
                    return;
                }
                currentPlayer = humanPlayer;
                document.getElementById('status').textContent = '你的回合（黑棋）';
                document.getElementById('status').style.color = 'black';
            }
        }

        // 核心AI逻辑（简单防守型）
        function findBestMove() {
            let candidates = [];
            let maxScore = -1;

            // 遍历所有空位评分
            for(let i=0; i<15; i++) {
                for(let j=0; j<15; j++) {
                    if(board[i][j] === 0) {
                        let score = evaluatePosition(i, j, aiPlayer);
                        score += evaluatePosition(i, j, humanPlayer)*0.8; // 重视防守
                        
                        if(score > maxScore) {
                            maxScore = score;
                            candidates = [{row:i, col:j}];
                        } else if(score === maxScore) {
                            candidates.push({row:i, col:j});
                        }
                    }
                }
            }
            
            // 随机选择最佳候选
            return candidates.length > 0 ? 
                candidates[Math.floor(Math.random()*candidates.length)] : 
                null;
        }

        // 位置评分函数
        function evaluatePosition(x, y, player) {
            let score = 0;
            const dirs = [[1,0],[0,1],[1,1],[1,-1]]; // 四个方向
            
            dirs.forEach(([dx, dy]) => {
                let count = 1;    // 当前空位算1
                let openEnds = 0; // 开放端点数量
                
                // 正向检测
                let i = x + dx, j = y + dy;
                while(i>=0 && i<15 && j>=0 && j<15) {
                    if(board[i][j] === player) count++;
                    else {
                        if(board[i][j] === 0) openEnds++;
                        break;
                    }
                    i += dx;
                    j += dy;
                }
                
                // 反向检测
                i = x - dx;
                j = y - dy;
                while(i>=0 && i<15 && j>=0 && j<15) {
                    if(board[i][j] === player) count++;
                    else {
                        if(board[i][j] === 0) openEnds++;
                        break;
                    }
                    i -= dx;
                    j -= dy;
                }
                
                // 评分规则
                if(count >= 5) score += 100000; // 连五
                else if(count === 4 && openEnds > 0) score += openEnds * 1000; // 活四/冲四
                else if(count === 3 && openEnds > 0) score += openEnds * 100;  // 活三
                else if(count === 2 && openEnds > 0) score += openEnds * 10;   // 活二
            });
            
            return score;
        }

        // 公共方法
        function placeStone(row, col, player) {
            board[row][col] = player;
            const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
            const stone = document.createElement('div');
            stone.className = `stone ${player === 1 ? 'black' : 'white'}`;
            cell.appendChild(stone);
        }

        function checkWin(row, col) {
            const player = board[row][col];
            const dirs = [[[0,1],[0,-1]], [[1,0],[-1,0]], [[1,1],[-1,-1]], [[1,-1],[-1,1]]];
            
            for(let dir of dirs) {
                let count = 1;
                for(let d of dir) {
                    let i = row + d[0], j = col + d[1];
                    while(i>=0 && i<15 && j>=0 && j<15 && board[i][j] === player) {
                        count++;
                        i += d[0];
                        j += d[1];
                    }
                }
                if(count >= 5) return true;
            }
            return false;
        }

        function resetGame() {
            board.forEach(row => row.fill(0));
            currentPlayer = humanPlayer;
            gameOver = false;
            document.getElementById('status').textContent = '你的回合（黑棋）';
            initBoard();
        }

        initBoard();
    </script>
</body>
</html>